package com.tulele.vtool.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.tulele.vtool.mapper.*;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.*;
import com.tulele.vtool.model.reqEntity.GetArticleInfoByArticleReqBean;
import com.tulele.vtool.model.respEntity.ArticleRespEntity;
import com.tulele.vtool.service.*;
import com.tulele.vtool.task.async.LookArticleAsyncTask;
import com.tulele.vtool.task.async.LookPunchClockArticleAsyncTask;
import com.tulele.vtool.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArticleInfoServiceImpl implements IArticleInfoService {

    @Autowired
    private ILookArticleInfoService lookArticleInfoService;

    @Autowired
    private ArticleInfoMapper articleInfoMapper;

    @Autowired
    private INewLookArticleCountInfoService newLookArticleCountInfoService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    @Lazy
    private LookArticleAsyncTask lookArticleAsyncTask;

    @Autowired
    @Lazy
    private LookPunchClockArticleAsyncTask lookPunchClockArticleAsyncTask;

//    @Autowired
//    private PlatformSysInfoConfig platformSysInfoConfig;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserBrandInfoService userBrandInfoService;

    @Autowired
    private IUserArticleTypeInfoService userArticleTypeInfoService;

    @Autowired
    private BrandInfoMapper brandInfoMapper;

    @Autowired
    private ArticleTypeInfoMapper articleTypeInfoMapper;

    @Autowired
    private UserBrandInfoMapper userBrandInfoMapper;

    @Autowired
    private ConnectionInfoService connectionInfoService;

    @Autowired
    private BrandSupplyInfoMapper brandSupplyInfoMapper;

    @Autowired
    private WxNotifyMsgSetInfoMapper wxNotifyMsgSetInfoMapper;

    @Autowired
    private ArticleTailSetInfoMapper articleTailSetInfoMapper;

//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

    @Override
    public int addWechatArticleInfo(ArticleInfo articleInfo) {
        articleInfoMapper.addArticleInfo(articleInfo);
        // 设置用户文章底部开关的开启状态
        saveUserArticleTailSetInfo(articleInfo.getUserId(), articleInfo.getId());
        return articleInfo.getId();
    }

    @Override
    public int modifyWechatArticleInfo(ArticleInfo articleInfo) {

        String cacheKey = articleInfo.getId() + "ArticleDetailInfoKey";
        //redisCacheUtil.removeSingleCache(cacheKey);  //屏蔽于 20200509
        redisCacheUtil.removeSingleCacheMaster(cacheKey);

        return articleInfoMapper.updateArticleInfo(articleInfo);
    }

    @Override
    public int addUserArticleInfo(ArticleInfo articleInfo) {
        articleInfoMapper.addArticleInfo(articleInfo);
        // 设置用户文章底部开关的开启状态
        saveUserArticleTailSetInfo(articleInfo.getUserId(), articleInfo.getId());
        return articleInfo.getId();
    }

    @Override
    public int modifyUserArticleInfo(ArticleInfo articleInfo) {

        String cacheKey = articleInfo.getId() + "ArticleDetailInfoKey";
        //redisCacheUtil.removeSingleCache(cacheKey);  //屏蔽于20200509
        redisCacheUtil.removeSingleCacheMaster(cacheKey);

        return articleInfoMapper.updateArticleInfo(articleInfo);
    }

    @Override
    public ArticleInfo getArticleDetailByInfo(Integer articleId) {
        String cacheKey = articleId + "ArticleDetailInfoKey";

        ArticleInfo articleInfo = articleInfoMapper.queryArticleDetailInfo(articleId);

        if (articleInfo != null) {
            redisCacheUtil.removeSingleCacheMaster(cacheKey);

            redisCacheUtil.setCacheObjectMaster(cacheKey, articleInfo, 172800);

        }

        return articleInfoMapper.queryArticleDetailInfo(articleId);
    }

    @Override
    public ArticleInfo getArticleDetailInfo(Integer articleId) {

        String cacheKey = articleId + "ArticleDetailInfoKey";
        //Object articleDetailInfoInfoObj = redisCacheUtil.getCacheObject(cacheKey);  //屏蔽于20200509
        Object articleDetailInfoInfoObj = redisCacheUtil.getCacheObjectMaster(cacheKey);

        ArticleInfo articleInfo = new ArticleInfo();
        if (articleDetailInfoInfoObj == null ||
                (articleDetailInfoInfoObj != null &&
                        (((ArticleInfo)articleDetailInfoInfoObj).getId()==null ||
                                ((ArticleInfo)articleDetailInfoInfoObj).getArticleTitle()==null ||
                                ((ArticleInfo)articleDetailInfoInfoObj).getArticleContent()==null ||
                                ( ((ArticleInfo)articleDetailInfoInfoObj).getResourceType()==2 && ((ArticleInfo)articleDetailInfoInfoObj).getVideoHeight()==null  )))) {
            articleInfo = articleInfoMapper.queryArticleDetailInfo(articleId);

            if (articleInfo == null) {

                //屏蔽于20200419
                //redisCacheUtil.setCacheObject(cacheKey, new ArticleInfo(), 172800);//原来是2592000(30天)，20200405 改为 172800
                redisCacheUtil.removeSingleCacheMaster(cacheKey);
            } else {

                redisCacheUtil.setCacheObjectMaster(cacheKey, articleInfo, 172800);//原来是2592000(30天)，20200405 改为 172800

            }

        } else {

            articleInfo = (ArticleInfo)articleDetailInfoInfoObj;

        }

        return articleInfo;

    }

    @Override
    public PageInfo<CombinedUserLookOtherArticleInfo> getUserLookOtherArticleInfo(Integer pageNum, Integer pageSize, LookArticleInfo lookArticleInfo) {

        //获取用户查看的文章信息时，把对应的文章查看次数清空
        NewLookArticleCountInfo newLookArticleCountInfo = new NewLookArticleCountInfo();
        newLookArticleCountInfo.setUserId(lookArticleInfo.getUserId());
        newLookArticleCountInfo.setOtherUserId(lookArticleInfo.getOtherUserId());
        newLookArticleCountInfoService.modifyUserNewLookArticleInfo(newLookArticleCountInfo);

        PageHelper.startPage(pageNum, pageSize);
        List<CombinedUserLookOtherArticleInfo> userLookOtherArticleInfoList = articleInfoMapper.queryUserLookOtherArticleInfo(lookArticleInfo);

        return new PageInfo<CombinedUserLookOtherArticleInfo>(userLookOtherArticleInfoList);
    }

    @Override
    public PageInfo<CombinedArticleInfoByArticleBrand> getArticleInfoByBrand(Integer pageNum, Integer pageSize, Integer userId) {
        PageHelper.startPage(pageNum, pageSize);
        List<CombinedArticleInfoByArticleBrand> articleInfoByArticleBrandList = articleInfoMapper.queryArticleInfoByBrand(userId);

        return new PageInfo<CombinedArticleInfoByArticleBrand>(articleInfoByArticleBrandList);
    }

    @Override
    public PageInfo<CombinedArticleInfoByArticleType> getArticleInfoByArticleType(Integer pageNum, Integer pageSize, Integer articleTypeId) {
        PageHelper.startPage(pageNum, pageSize);
        List<CombinedArticleInfoByArticleType> articleInfoByArticleTypeList = articleInfoMapper.queryArticleInfoByArticleType(articleTypeId);

        return new PageInfo<CombinedArticleInfoByArticleType>(articleInfoByArticleTypeList);
    }

    @Override
    public List<CombinedUserArticleInfoBySpecialSize> getUserArticleInfoBySpecialSize(Integer userId, int recordSize) {
        return articleInfoMapper.queryUserArticleInfoBySpecialSize(userId, recordSize);
    }

    @Override
    public PageInfo<CombinedUserOwnArticleInfo> getUserOwnArticleInfo(Integer pageNum, Integer pageSize, Integer userId) {
        PageHelper.startPage(pageNum, pageSize);
        List<CombinedUserOwnArticleInfo> userOwnArticleInfoList = articleInfoMapper.queryUserOwnArticleInfo(userId);

        return new PageInfo<CombinedUserOwnArticleInfo>(userOwnArticleInfoList);
    }

    @Override
    public int removeUserArticleInfo(ArticleInfo articleInfo) {




        String cacheKey = articleInfo.getId() + "ArticleDetailInfoKey";
        //redisCacheUtil.removeSingleCache(cacheKey);  //屏蔽于20200509
        redisCacheUtil.removeSingleCacheMaster(cacheKey);

        return articleInfoMapper.updateArticleInfo(articleInfo);
    }

    @Override
    public Integer getArticleUserInfo(Integer articleId) {
        return articleInfoMapper.queryArticleUserInfo(articleId);
    }

    @Override
    public Integer lookOtherUserArticle(LookArticleInfo lookArticleInfo, ArticleInfo articleInfo, String lookUserNickName, String viewType,String springProfilesActive) throws Exception {

        log.info("********** ArticleInfoServiceImpl lookOtherUserArticle"+",[lookArticleInfo]="+lookArticleInfo.toString()+",[articleInfo]="+articleInfo.toString()+",[lookUserNickName]="+lookUserNickName+",[viewType]="+viewType);
        ArticleInfo queryArticleInfo = new ArticleInfo();
        queryArticleInfo.setShareArticleSourceId(lookArticleInfo.getArticleId());
        queryArticleInfo.setUserId(lookArticleInfo.getOtherUserId());

        int finalArticleId = Optional.ofNullable(articleInfoMapper.queryUserPlatformArticleShareStatus(queryArticleInfo)).orElse(0);
        if (finalArticleId > 0) {
            lookArticleInfo.setArticleId(finalArticleId);
        }

        Integer lookArticleId = lookArticleAsyncTask.lookOtherUserArticle(lookArticleInfo, articleInfo, lookUserNickName, viewType,springProfilesActive);

        return lookArticleId;
    }

    @Override
    public Integer lookOtherUserArticleSyn(LookArticleInfo lookArticleInfo, ArticleInfo articleInfo, String lookUserNickName, String viewType,String springProfilesActive) throws Exception {

        //log.error("********** ArticleInfoServiceImpl lookOtherUserArticle"+",[lookArticleInfo]="+lookArticleInfo.toString()+",[articleInfo]="+articleInfo.toString()+",[lookUserNickName]="+lookUserNickName+",[viewType]="+viewType);
        ArticleInfo queryArticleInfo = new ArticleInfo();
        queryArticleInfo.setShareArticleSourceId(lookArticleInfo.getArticleId());
        queryArticleInfo.setUserId(lookArticleInfo.getOtherUserId());

        int finalArticleId = Optional.ofNullable(articleInfoMapper.queryUserPlatformArticleShareStatus(queryArticleInfo)).orElse(0);
        if (finalArticleId > 0) {
            lookArticleInfo.setArticleId(finalArticleId);
        }

        Integer lookArticleId = lookArticleAsyncTask.lookOtherUserArticleSyn(lookArticleInfo, articleInfo, lookUserNickName, viewType,springProfilesActive);

        return lookArticleId;
    }

    @Override
    public List<PlatformRecommendArticleInfo> getPlatformRecommendArticleInfo() {
        return articleInfoMapper.queryPlatformRecommendArticleInfo();
    }

    @Override
    public ArticleInfo getSpiderArticleInfoByThirdArticleId(ArticleInfo articleInfo) {
        return articleInfoMapper.querySpiderArticleInfoByThirdArticleId(articleInfo);
    }

    @Override
    public Integer getUserPlatformArticleShareStatus(ArticleInfo articleInfo) {
        return articleInfoMapper.queryUserPlatformArticleShareStatus(articleInfo);
    }

    @Override
    public Integer getPlatformArticleCountByBrandId(Integer brandId) {
        return articleInfoMapper.queryPlatformArticleCountByBrandId(brandId);
    }

    @Override
    public Integer getPlatformArticleCountByTypeId(Integer typeId) {
        return articleInfoMapper.queryPlatformArticleCountByTypeId(typeId);
    }

    @Override
    public List<ArticleInfo> getToBeProcessedSpiderArticleInfo() {
        return articleInfoMapper.queryToBeProcessedSpiderArticleInfo();
    }

    @Override
    public List<PlatformRecommendArticleInfo> getPlatformRecommendArticleInfoByBrand(List<Integer> useBrandIds) {
        return articleInfoMapper.queryPlatformRecommendArticleInfoByBrand(useBrandIds);
    }

    @Override
    public List<PlatformRecommendArticleInfo> getPlatformRecommendArticleInfoByType(Integer articleTypeId) {
        return articleInfoMapper.queryPlatformRecommendArticleInfoByType(articleTypeId);
    }

    @Override
    public List<PlatformRecommendArticleInfo> getPlatformRecommendArticleInfoByTypeAndRecordSize(Integer articleTypeId, Integer recordSize) {
        return articleInfoMapper.getPlatformRecommendArticleInfoByTypeAndRecordSize(articleTypeId, recordSize);
    }

    @Override
    public List<CombinedArticleInfoByArticleBrand> getArticleInfoByBrandForRand(Integer articleBrandId, int recordSize) {
        String articleBrandIdKey = "platformBrandArticle" + articleBrandId;


        //20200504

//        LettuceConnectionFactory factory =
//                (LettuceConnectionFactory) redisCacheUtil.redisTemplate.getConnectionFactory();
//
//        int oldDataBase= factory.getDatabase();
//        log.info("***** oldDataBase:"+oldDataBase);
//
//        factory.setDatabase(0);//切换到主数据库
//        redisCacheUtil.redisTemplate.setConnectionFactory(factory);
//        log.info("***** newDataBase:"+factory.getDatabase());
        //20200504

        Set<CombinedArticleInfoByArticleBrand> brandArticleInfoSet = redisCacheUtil.getMasterCacheSetForRandomEle(articleBrandIdKey, recordSize);

        List<CombinedArticleInfoByArticleBrand> brandArticleInfoList = Lists.newArrayList();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(brandArticleInfoSet)) {

            brandArticleInfoList = Lists.newArrayList(brandArticleInfoSet);

        }

//        factory.setDatabase(oldDataBase);//切换回来
//        redisCacheUtil.redisTemplate.setConnectionFactory(factory);
//        log.info("***** setOldDataBase:"+factory.getDatabase());

        return brandArticleInfoList;
    }

    @Override
    public List<CombinedArticleInfoByArticleBrand> getArticleInfoByArticleTypeForRand(Integer articleTypeId, int recordSize) {

        String articleTypeIdKey = "platformTypeArticle" + articleTypeId;

        //20200504
//        LettuceConnectionFactory factory =
//                (LettuceConnectionFactory) redisCacheUtil.redisTemplate.getConnectionFactory();
//
//        int oldDataBase= factory.getDatabase();
//        log.info("***** getArticleInfoByArticleTypeForRand oldDataBase:"+oldDataBase);
//
//        factory.setDatabase(0);//切换到主数据库
//        redisCacheUtil.redisTemplate.setConnectionFactory(factory);
//        log.info("***** getArticleInfoByArticleTypeForRand newDataBase:"+factory.getDatabase());
        //20200504

        Set<CombinedArticleInfoByArticleBrand> typeArticleInfoSet = redisCacheUtil.getMasterCacheSetForRandomEle(articleTypeIdKey, recordSize);

        List<CombinedArticleInfoByArticleBrand> typeArticleInfoList = Lists.newArrayList();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(typeArticleInfoSet)) {

            typeArticleInfoList = Lists.newArrayList(typeArticleInfoSet);

        }

//        factory.setDatabase(oldDataBase);//切换回来
//        redisCacheUtil.redisTemplate.setConnectionFactory(factory);
//        log.info("***** getArticleInfoByArticleTypeForRand oldSetDataBase:"+factory.getDatabase());

        return typeArticleInfoList;

        //return articleInfoMapper.queryArticleInfoByArticleTypeForRand(articleTypeId, recordSize);
    }

    @Override
    public int pseudoDeleteArticleInfo(Integer articleId) {
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setId(articleId);
        articleInfo.setArticleStatus(0);
        articleInfo.setModifyTime(DateUtil.getCurDate());
        return articleInfoMapper.updateArticleInfo(articleInfo);
    }

    /*ljt 20201027 start*/
    /**
     * 根据用户关注的文章类型id倒序查询文章信息
     *
     * @param pageNum 查询起始位置
     * @param pageSize  查询条数
     * @param integerList 实例对象
     * @return 对象列表
     */
    @Override
    public PageInfo selectAllByLimit(Integer pageNum, Integer pageSize, List<Integer> integerList) {

        PageHelper.startPage(pageNum, pageSize);

        List<CombinedArticleInfoByArticleBrand> articleInfoList = this.articleInfoMapper.queryAllByTypeIds(integerList);

        return new PageInfo<CombinedArticleInfoByArticleBrand>(articleInfoList);
    }
    /*ljt 20201027 end*/

    @Override
    public List<CombinedArticleInfoByArticleBrand> getArticleInfoByUserConcernArticleTypeForRand(List<Integer> articleTypeId, int recordSize) {

        String articleTypeIdKey = "platformTypeArticle" + articleTypeId.get(0);

        //20200504
//        LettuceConnectionFactory factory =
//                (LettuceConnectionFactory) redisCacheUtil.redisTemplate.getConnectionFactory();
//
//        int oldDataBase= factory.getDatabase();
//        log.info("***** getArticleInfoByUserConcernArticleTypeForRand oldDataBase:"+oldDataBase);
//
//        factory.setDatabase(0);//切换到主数据库
//        redisCacheUtil.redisTemplate.setConnectionFactory(factory);
//        log.info("***** getArticleInfoByUserConcernArticleTypeForRand newDataBase:"+factory.getDatabase());
        //20200504

        Set<CombinedArticleInfoByArticleBrand> typeArticleInfoSet = redisCacheUtil.getMasterCacheSetForRandomEle(articleTypeIdKey, recordSize);

        List<CombinedArticleInfoByArticleBrand> typeArticleInfoList = Lists.newArrayList();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(typeArticleInfoSet)) {

            typeArticleInfoList = Lists.newArrayList(typeArticleInfoSet);

        }

//        factory.setDatabase(oldDataBase);//切换回来
//        redisCacheUtil.redisTemplate.setConnectionFactory(factory);
//        log.info("***** getArticleInfoByUserConcernArticleTypeForRand oldSetDataBase:"+factory.getDatabase());

        return typeArticleInfoList;

        //return articleInfoMapper.queryArticleInfoByUserArticleTypeForRand(articleTypeId, recordSize);
    }

    @Override
    public String generateUserPushArticleInfo(List<Integer> articleTypeId, int recordSize,PlatformSysInfo platformSysInfoConfig) {

        String articleDetailUrl = platformSysInfoConfig.getArticleDetailUrl();

        StringBuffer wxPushMsg = new StringBuffer();
        wxPushMsg.append("公众号将继续为你推送消息\n\n");

        //List<CombinedArticleInfoByArticleType> articleInfoList = articleInfoMapper.queryArticleInfoByUserArticleTypeForRand(articleTypeId, recordSize);

        List<ArticleListShowInfo> articleInfoList = Lists.newArrayList();

        List<ArticleListShowInfo> articleListShowInfos_one = articleInfoMapper.queryArticleInfoByArticleTypeForHotScoreBySpecialSize(1, null, 1);

        List<ArticleListShowInfo> articleListShowInfos_two = articleInfoMapper.queryArticleInfoByArticleTypeForHotScoreBySpecialSize(4, null, 1);

        List<ArticleListShowInfo> articleListShowInfos_three = articleInfoMapper.queryArticleInfoByArticleTypeForHotScoreBySpecialSize(5, null, 1);

        List<ArticleListShowInfo> articleListShowInfos_four = articleInfoMapper.queryArticleInfoByArticleTypeForHotScoreBySpecialSize(9, null, 1);

        articleInfoList.addAll(articleListShowInfos_one);
        articleInfoList.addAll(articleListShowInfos_two);
        articleInfoList.addAll(articleListShowInfos_three);
        articleInfoList.addAll(articleListShowInfos_four);

        if (!CollectionUtils.isEmpty(articleInfoList)) {

            articleInfoList.forEach(articleInfo -> {
                wxPushMsg.append("\ue11d<a href='"+ articleDetailUrl + articleInfo.getArticleId() + "'>"+ articleInfo.getArticleTitle() +"</a>\n\n");
            });

        }

        wxPushMsg.append("点击下方 获客爆文，更多爆文");

        return wxPushMsg.toString();
    }

    @Override
    public List<CombinedArticleInfoByArticleBrand> getToBeAddRedisArticleInfoOfBrand() {
        return articleInfoMapper.queryToBeAddToRedisArticleInfoOfBrand();
    }

    @Override
    public List<CombinedArticleInfoByArticleBrand> getToBeRemoveRedisArticleInfoOfBrand() {
        return articleInfoMapper.queryToBeRemoveFromRedisArticleInfoOfBrand();
    }

    @Override
    public List<CombinedArticleInfoByArticleBrand> getToBeAddToRedisArticleInfoOfType() {
        return articleInfoMapper.queryToBeAddToRedisArticleInfoOfType();
    }

    @Override
    public List<CombinedArticleInfoByArticleBrand> getToBeRemoveFromRedisArticleInfoOfType() {
        return articleInfoMapper.queryToBeRemoveFromRedisArticleInfoOfType();
    }

    @Override
    public int lookOtherUserPunchClockArticle(LookArticleInfo lookArticleInfo, PunchClockArticleInfo punchClockArticleInfo, String lookUserNickName) {
        log.info("********** ArticleInfoServiceImpl lookOtherUserPunchClockArticle"+",[lookArticleInfo]="+lookArticleInfo.toString()+",[punchClockArticleInfo]="+punchClockArticleInfo.toString()+",[lookUserNickName]="+lookUserNickName);
        //查询是否已经有了查看记录
        LookArticleInfo lookArticleInfoInDB = lookArticleInfoService.getLookOtherArticleInfo(lookArticleInfo);
        if (lookArticleInfoInDB == null) {

            LookArticleInfo recordLookArticleInfo = new LookArticleInfo();
            recordLookArticleInfo.setUserId(lookArticleInfo.getUserId());
            recordLookArticleInfo.setOtherUserId(lookArticleInfo.getOtherUserId());
            recordLookArticleInfo.setArticleId(lookArticleInfo.getArticleId());
            recordLookArticleInfo.setLookCount(1);
            recordLookArticleInfo.setTodayLookCount(1);
            recordLookArticleInfo.setArticleCategory(2);
            recordLookArticleInfo.setCreateTime(DateUtil.getCurDate());
            recordLookArticleInfo.setModifyTime(DateUtil.getCurDate());

            //不存在，则添加
            lookArticleInfoService.recordLookArticleInfo(recordLookArticleInfo);

        } else {

            //存在，则修改
            int lookCount = Optional.ofNullable(lookArticleInfoInDB.getLookCount()).orElse(0);
            int todayLookCount = Optional.ofNullable(lookArticleInfoInDB.getTodayLookCount()).orElse(0);

            LookArticleInfo modifyLookArticleInfo = new LookArticleInfo();
            modifyLookArticleInfo.setId(lookArticleInfoInDB.getId());
            modifyLookArticleInfo.setTodayLookCount(todayLookCount + 1);
            modifyLookArticleInfo.setLookCount(lookCount + 1);
            modifyLookArticleInfo.setModifyTime(DateUtil.getCurDate());

            lookArticleInfoService.modifyLookArticleInfo(modifyLookArticleInfo);

        }

        //记录新的查看次数
        NewLookArticleCountInfo newLookArticleCountInfo = new NewLookArticleCountInfo();
        newLookArticleCountInfo.setUserId(lookArticleInfo.getUserId());
        newLookArticleCountInfo.setOtherUserId(lookArticleInfo.getOtherUserId());

        NewLookArticleCountInfo newLookArticleCountInfoInDB = newLookArticleCountInfoService.getNewLookArticleInfo(newLookArticleCountInfo);
        if (newLookArticleCountInfoInDB != null && newLookArticleCountInfoInDB.getId() != null) {

            NewLookArticleCountInfo updateNewLookArticleCountInfo = new NewLookArticleCountInfo();
            updateNewLookArticleCountInfo.setId(newLookArticleCountInfoInDB.getId());
            updateNewLookArticleCountInfo.setLookCount(newLookArticleCountInfoInDB.getLookCount() + 1);
            updateNewLookArticleCountInfo.setModifyTime(DateUtil.getCurDate());

            newLookArticleCountInfoService.modifyNewLookArticleInfo(updateNewLookArticleCountInfo);

        } else {

            newLookArticleCountInfo.setLookCount(1);
            newLookArticleCountInfo.setModifyTime(DateUtil.getCurDate());
            newLookArticleCountInfo.setCreateTime(DateUtil.getCurDate());

            newLookArticleCountInfoService.recordNewLookArticleInfo(newLookArticleCountInfo);

        }

        //发送微信公众号通知
        //lookPunchClockArticleAsyncTask.sendUserPunchClockArticleBeLookedWxPushMsg(lookArticleInfo.getUserId(), lookArticleInfo.getOtherUserId(), punchClockArticleInfo, lookUserNickName);

        return 0;
    }

    @Override
    public List<CombinedArticleInfoByArticleBrand> tempQueryThumbnailNullInfo() {
        return articleInfoMapper.tempQueryThumbnailNullInfo();
    }

    @Override
    public int getUserSharedArticleCount(Integer userId) {

        int userSharedArticleCount = 0;

        Object userSharedArticleCountObj = redisCacheUtil.getCacheObject("userSharedArticleCount" + userId);
        if (userSharedArticleCountObj != null) {
            userSharedArticleCount = (Integer)userSharedArticleCountObj;
        } else {
            userSharedArticleCount = Optional.ofNullable(articleInfoMapper.queryUserSharedArticleCount(userId)).orElse(0);
        }

        //因为前端只需要知道用户是否已经分享过文章，故只要查询到用户分享数目大于1，则缓存
        if (userSharedArticleCount > 1) {

            redisCacheUtil.setCacheObject("userSharedArticleCount" + userId, userSharedArticleCount, 2592000);

        }

        return userSharedArticleCount;
    }

    @Override
    public void insertArticleInfoByArticleType( Integer articleTypeId,String springProfilesActive) {
        articleInfoMapper.insertArticleInfoByArticleType(articleTypeId, springProfilesActive);
    }

    @Override
    public PageInfo<ArticleListShowInfo> getArticleInfoByArticleTypeForHotScore(int pageNum, int pageSize, Integer articleTypeId, Integer articleHotValue,String springProfilesActive) {

        PageHelper.startPage(pageNum, pageSize);

        //兼容测试环境sql版本
        if(springProfilesActive.equals("test")){
            List<ArticleListShowInfo> articleInfoByArticleTypeList = articleInfoMapper.queryArticleInfoByArticleTypeForHotScoreTest(articleTypeId, articleHotValue,springProfilesActive);

            return new PageInfo<ArticleListShowInfo>(articleInfoByArticleTypeList);
        }

        List<ArticleListShowInfo> articleInfoByArticleTypeList = articleInfoMapper.queryArticleInfoByArticleTypeForHotScore(articleTypeId, articleHotValue,springProfilesActive);

        return new PageInfo<ArticleListShowInfo>(articleInfoByArticleTypeList);
    }

    @Override
    public void insertArticleInfoByArticleBrand( Integer articleBrandId) {
        articleInfoMapper.insertArticleInfoByArticleBrand(articleBrandId);
    }

    @Override
    public PageInfo<ArticleListShowInfo> getArticleInfoByArticleBrandForHotScore(int pageNum, int pageSize, Integer articleBrandId, Integer articleHotValue,String springProfilesActive) {

        PageHelper.startPage(pageNum, pageSize);

        //兼容测试环境sql版本
        if(springProfilesActive.equals("test")){
            List<ArticleListShowInfo> articleInfoByArticleBrandList =  articleInfoMapper.queryArticleInfoByArticleBrandForHotScoreTest(articleBrandId, articleHotValue);

            return new PageInfo<ArticleListShowInfo>(articleInfoByArticleBrandList);
        }

        List<ArticleListShowInfo> articleInfoByArticleBrandList =  articleInfoMapper.queryArticleInfoByArticleBrandForHotScore(articleBrandId, articleHotValue,springProfilesActive);

        return new PageInfo<ArticleListShowInfo>(articleInfoByArticleBrandList);
    }

    @Override
    public PageInfo<ArticleListShowInfo> queryArticleInfoByKeyWorksForHotScore(int pageNum, int pageSize, String keyWorks) {

        PageHelper.startPage(pageNum, pageSize);
        List<ArticleListShowInfo> articleInfoByKeyWorksList =  articleInfoMapper.queryArticleInfoByKeyWorksForHotScore(keyWorks);

        return new PageInfo<ArticleListShowInfo>(articleInfoByKeyWorksList);
    }



    @Override
    public List<ArticleListShowInfo> getArticleInfoByArticleTypeForHotScoreBySpecialSize(Integer articleTypeId, Integer articleHotValue, Integer recordSize) {
        return articleInfoMapper.queryArticleInfoByArticleTypeForHotScoreBySpecialSize(articleTypeId, articleHotValue, recordSize);
    }

    @Override
    public ArticleInfo getUserAddedWxArticleInfoByTitle(Integer userId, String articleTitle) {
        return articleInfoMapper.queryUserAddedWxArticleInfoByTitle(userId, articleTitle);
    }

    @Override
    public String generateCustomerPagePromptText(Integer userId, int totalLookCount) {

        CustomerPagePromptInfo customerPagePromptInfo = (CustomerPagePromptInfo) redisCacheUtil.getCacheObject(userId + "customerPagePushTimesKey");

        int customerPagePushTimes = 1;
        if (customerPagePromptInfo == null) {
            customerPagePromptInfo = new CustomerPagePromptInfo();
            customerPagePromptInfo.setLastPushTime(1);
            customerPagePromptInfo.setNextPushTime(2);

            String pushDate = DateTime.now().toString("yyyy-MM-dd");
            customerPagePromptInfo.setLastPushDate(pushDate);

            redisCacheUtil.setCacheObject(userId + "customerPagePushTimesKey", customerPagePromptInfo, 604800);

        } else {

            String pushDate = customerPagePromptInfo.getLastPushDate();

            String nowDate = DateTime.now().toString("yyyy-MM-dd");

            if (nowDate.equals(pushDate)) {

                customerPagePushTimes = customerPagePromptInfo.getLastPushTime();

            } else {

                customerPagePushTimes = customerPagePromptInfo.getNextPushTime();

                CustomerPagePromptInfo nextCustomerPagePromptInfo = new CustomerPagePromptInfo();

                nextCustomerPagePromptInfo.setLastPushTime(customerPagePromptInfo.getNextPushTime());
                nextCustomerPagePromptInfo.setNextPushTime(customerPagePromptInfo.getNextPushTime() + 1);
                nextCustomerPagePromptInfo.setLastPushDate(nowDate);

                redisCacheUtil.setCacheObject(userId + "customerPagePushTimesKey", nextCustomerPagePromptInfo, 604800);

            }

        }

        StringBuffer promptText = new StringBuffer();
        if (customerPagePushTimes == 1 || customerPagePushTimes == 8) {

            promptText.append("你已错过");
            promptText.append(totalLookCount);
            promptText.append("次跟进机会\n");
            promptText.append("客户都白白浪费了！");

        } else if (customerPagePushTimes == 2) {

            if (totalLookCount > 5) {

                promptText.append("有");
                promptText.append(totalLookCount);
                promptText.append("个意向客户看了你的文章\n");
                promptText.append("精准机会就这么错过？");

            } else {

                promptText.append("有意向客户看了你的文章\n");
                promptText.append("不能错过这么精准的机会哦~");

            }

        } else if (customerPagePushTimes == 3) {

            //获取用户选中的品牌
            BrandInfo selectBrandInfo = userBrandInfoService.getUserSelectBrandInfo(userId);

            if (selectBrandInfo == null || selectBrandInfo.getId() == null || selectBrandInfo.getUserId() != null) {

                promptText.append("你的同行都在追踪客户哦\n");
                promptText.append("你也要行动哦，不能被动等待");

            } else {
                int brandId = selectBrandInfo.getId();
                int brandSubCount = userBrandInfoService.getBrandSubCount(brandId);
                String brandName = selectBrandInfo.getBrandName();

                if (brandSubCount < 30) {
                    promptText.append(brandName);
                    promptText.append(" 的小伙伴都在追踪客户哦\n");
                    promptText.append("你也要行动哦，不能被动等待");
                } else {

                    promptText.append(brandName);
                    promptText.append("已有 ");
                    promptText.append(brandSubCount * 15);
                    promptText.append(" 人在追踪客户哦\n");
                    promptText.append("你也要行动哦，不能被动等待");

                }

            }

        } else if (customerPagePushTimes == 4) {

            promptText.append("最容易成交的就是朋友圈客户啊~\n");
            promptText.append("先从身边的资源开始吧");

        } else if (customerPagePushTimes == 5) {

            promptText.append("已有 ");
            promptText.append(totalLookCount);
            promptText.append(" 人看了你的文章\n");
            promptText.append("你还说没客户资源吗？");

        } else if (customerPagePushTimes == 6) {

            promptText.append("天天想着加好友是没错\n");
            promptText.append("可了解客户需求才最关键呢");

        } else if (customerPagePushTimes == 7) {

            //获取用户选中的品牌
            BrandInfo selectBrandInfo = userBrandInfoService.getUserSelectBrandInfo(userId);

            if (selectBrandInfo == null || selectBrandInfo.getId() == null || selectBrandInfo.getUserId() != null) {

                promptText.append("有其他伙伴开通会员了哦\n");
                promptText.append("你还在茫然的想客户在哪...");

            } else {

                int brandId = selectBrandInfo.getId();
                int brandSubCount = userBrandInfoService.getBrandSubCount(brandId);
                String brandName = selectBrandInfo.getBrandName();

                if (brandSubCount < 100) {

                    promptText.append(brandName);
                    promptText.append(" 有 ");
                    promptText.append(1 + brandSubCount / 10);
                    promptText.append(" 位伙伴开会员了哦\n");
                    promptText.append("你还在茫然的想客户在哪...");

                } else {

                    int num = ToolUtil.randomNum(11, 29);

                    promptText.append(brandName);
                    promptText.append(" 有 ");
                    promptText.append(num + brandSubCount / 20);
                    promptText.append(" 位伙伴开会员了哦\n");
                    promptText.append("你还在茫然的想客户在哪...");

                }

            }

        }

        return promptText.toString();
    }

    @Override
    public List<ArticleInfo> selectArticleByVideo(List<Integer> ids, List<Integer> bid,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return this.articleInfoMapper.selectArticleByVideo(ids,bid);
    }

    @Override
    public List<ArticleInfo> selectArticleByArticleType(List<Integer> articleTypeId, Integer pageNum ,Integer pageSize) {
            PageHelper.startPage(pageNum, pageSize);
        String ids = Joiner.on(",").join(articleTypeId);
        return articleInfoMapper.selectArticleByArticleType(ids);
    }

    @Override
    public PageInfo selectArticleByArticleTypeAndBrandId(List<Integer> articleTypeId, List<Integer> userBrandIds, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleInfo> articleInfos = articleInfoMapper.selectArticleByArticleTypeAndBrandId(articleTypeId,userBrandIds);
        PageInfo pageInfo = new PageInfo(articleInfos);
        return pageInfo;
    }

    @Override
    public List<ArticleRespEntity> selectArticleByMaterial(Integer pageNum, Integer pageSize, GetArticleInfoByArticleReqBean articleInfoByArticleReqBean, Integer userId) {
        // 通过品牌id查询素材
        if (null != articleInfoByArticleReqBean.getArticleBrandId()){
            PageHelper.startPage(pageNum, pageSize);
           List<ArticleInfo>  articleInfos =this.articleInfoMapper.selectMaterialByBrandId(articleInfoByArticleReqBean.getArticleBrandId());
            if (CollectionUtils.isEmpty(articleInfos)){
                return null;
            }
            return articleInfos.stream().map(articleInfo -> {
                ArticleRespEntity articleRespEntity = new ArticleRespEntity();
                articleRespEntity.setId(articleInfo.getId());
                articleRespEntity.setVideoUrl(articleInfo.getVideoUrl());
                articleRespEntity.setHotType(articleInfo.getHotType());

                //String materialVideoFormat = this.articleInfoMapper.selectMaterialVideoFormat(articleInfo.getId());
                //if (StringUtils.isNotBlank(materialVideoFormat)){
                    //articleRespEntity.setVideoFormat("200"); // 此字段用于前端控制 值随意
                //}else{
                    articleRespEntity.setVideoFormat("400"); // 此字段用于前端控制 值随意
                //}

                articleRespEntity.setArticleDesc(articleInfo.getArticleDesc());
                articleRespEntity.setArticleShareCount(articleInfo.getArticleShareCount());
                // 相差分钟数
                articleRespEntity.setTimeDifference( this.timeDiffe(articleInfo.getCreateTime()));
               // 查询品牌名称和头像
               BrandInfo brandInfo = this.brandInfoMapper.selectBrandNameAndBrandHeadByBrandId(articleInfoByArticleReqBean.getArticleBrandId());
               if (null != brandInfo){
                   articleRespEntity.setHeadName(brandInfo.getBrandName());
                   articleRespEntity.setHeadImgUrl(brandInfo.getBrandLogo());
               }
               // 点赞数量
                // articleRespEntity.setLikeNum(this.articleInfoMapper.selectLikeNum(articleInfo.getId()));
                articleRespEntity.setLikeNum(0);
               // 素材图片
                String materialImgUrl = this.articleInfoMapper.selectMaterialImgUrl(articleInfo.getId());
                if (StringUtils.isNotBlank(materialImgUrl)){
                    articleRespEntity.setMaterialImgUrls(Arrays.asList(materialImgUrl.split(",")));
                }
                // 是否已经点赞
                //articleRespEntity.setIsLike(this.articleInfoMapper.isLike(userId,articleInfo.getId()));
                articleRespEntity.setIsLike(0);
                articleRespEntity.setResourceType(3);
                articleRespEntity.setVideoSize("1"); // 此字段用于前端控制 值随意
                return articleRespEntity;
            }).collect(Collectors.toList());

        }
        // 通过分类id查询
        if (null != articleInfoByArticleReqBean.getArticleTypeId()){
            PageHelper.startPage(pageNum, pageSize);
            List<ArticleInfo>  articleInfos = this.articleInfoMapper.selectMaterialByArticleTypeId(articleInfoByArticleReqBean.getArticleTypeId());
            if (CollectionUtils.isEmpty(articleInfos)){
                return null;
            }
            return articleInfos.stream().map(articleInfo -> {
                ArticleRespEntity articleRespEntity = new ArticleRespEntity();
                articleRespEntity.setId(articleInfo.getId());
                articleRespEntity.setVideoUrl(articleInfo.getVideoUrl());
                articleRespEntity.setHotType(articleInfo.getHotType());

//                String materialVideoFormat = this.articleInfoMapper.selectMaterialVideoFormat(articleInfo.getId());
//                if (StringUtils.isNotBlank(materialVideoFormat)){
//                    articleRespEntity.setVideoFormat("200"); // 此字段用于前端控制 值随意
//                }else{
                    articleRespEntity.setVideoFormat("400"); // 此字段用于前端控制 值随意
//                }

                articleRespEntity.setArticleDesc(articleInfo.getArticleDesc());
                articleRespEntity.setArticleShareCount(articleInfo.getArticleShareCount());
                // 相差分钟数
                articleRespEntity.setTimeDifference( this.timeDiffe(articleInfo.getCreateTime()));
                // 查询分类名称和头像
                ArticleTypeInfo articleTypeInfo = this.articleTypeInfoMapper.selectBrandNameAndBrandHeadByTypeId(articleInfoByArticleReqBean.getArticleTypeId());
                if (null != articleTypeInfo){
                    articleRespEntity.setHeadName(articleTypeInfo.getArticleTypeName());
                    articleRespEntity.setHeadImgUrl(articleTypeInfo.getArticleTypeLogo());
                }
                // 点赞数量
                //articleRespEntity.setLikeNum(this.articleInfoMapper.selectLikeNum(articleInfo.getId()));
                articleRespEntity.setLikeNum(0);
                // 素材图片
                String materialImgUrl = this.articleInfoMapper.selectMaterialImgUrl(articleInfo.getId());
                if (StringUtils.isNotBlank(materialImgUrl)){
                    articleRespEntity.setMaterialImgUrls(Arrays.asList(materialImgUrl.split(",")));
                }
                // 是否已经点赞
                //articleRespEntity.setIsLike(this.articleInfoMapper.isLike(userId,articleInfo.getId()));
                articleRespEntity.setIsLike(0);
                articleRespEntity.setResourceType(3);
                articleRespEntity.setVideoSize("1"); // 此字段用于前端控制 值随意
                return articleRespEntity;
            }).collect(Collectors.toList());

        }
        // 无品牌id及分类id将返回关注的
        //-----------------------------------------------------------------------------------------
        // 用户关注的品牌
        List<UserBrandCombinedInfo> userBrandCombinedInfos = userBrandInfoMapper.queryUserBrandInfo(userId);
        // 关注的品牌id集合
        List<Integer> userBrandIds = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userBrandCombinedInfos)) {
            userBrandCombinedInfos.stream().forEach(info -> {
                userBrandIds.add(info.getBrandId());
            });
        }
        // 关注的类型id集合
        List<Integer> userConcernArticleTypeIds = Lists.newArrayList();
        List<ArticleTypeInfo>  articleTypeInfos = this.articleTypeInfoMapper.selectUserAttentionMaterialType(userId);
        if (CollectionUtils.isNotEmpty(articleTypeInfos)){
            userConcernArticleTypeIds = articleTypeInfos.stream().map(ArticleTypeInfo::getId).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(userConcernArticleTypeIds)) {
            userConcernArticleTypeIds = userArticleTypeInfoService.getUserConcernArticleTypeInfo(userId);
            if (userConcernArticleTypeIds == null) {
                userConcernArticleTypeIds = Lists.newArrayList();
            }
            userConcernArticleTypeIds.add(1);//这里确保了不能为空
        }
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleInfo>  articleInfos = this.articleInfoMapper.selectArticleByUserAttention(userBrandIds,userConcernArticleTypeIds);
        if (CollectionUtils.isNotEmpty(articleInfos)){
            return articleInfos.stream().map(articleInfo -> {
                ArticleRespEntity articleRespEntity = new ArticleRespEntity();
                articleRespEntity.setId(articleInfo.getId());
                articleRespEntity.setVideoUrl(articleInfo.getVideoUrl());
                articleRespEntity.setHotType(articleInfo.getHotType());

//                String materialVideoFormat = this.articleInfoMapper.selectMaterialVideoFormat(articleInfo.getId());
//                if (StringUtils.isNotBlank(materialVideoFormat)){
//                    articleRespEntity.setVideoFormat("200"); // 此字段用于前端控制 值随意
//                }else{
                    articleRespEntity.setVideoFormat("400"); // 此字段用于前端控制 值随意
//                }

                articleRespEntity.setArticleDesc(articleInfo.getArticleDesc());
                articleRespEntity.setArticleShareCount(articleInfo.getArticleShareCount());
                // 相差分钟数
                articleRespEntity.setTimeDifference( this.timeDiffe(articleInfo.getCreateTime()));
                // 查询名称和头像
                if (null != articleInfo.getArticleBrandId()){
                    BrandInfo brandInfo = this.brandInfoMapper.selectBrandNameAndBrandHeadByBrandId(articleInfo.getArticleBrandId());
                    if (null != brandInfo){
                        articleRespEntity.setHeadName(brandInfo.getBrandName());
                        articleRespEntity.setHeadImgUrl(brandInfo.getBrandLogo());
                    }
                }
                if (null != articleInfo.getArticleTypeId()){
                    ArticleTypeInfo articleTypeInfo = this.articleTypeInfoMapper.selectBrandNameAndBrandHeadByTypeId(articleInfo.getArticleTypeId());
                    if (null != articleTypeInfo){
                        articleRespEntity.setHeadName(articleTypeInfo.getArticleTypeName());
                        articleRespEntity.setHeadImgUrl(articleTypeInfo.getArticleTypeLogo());
                    }
                }
                //articleRespEntity.setVideoUrl(this.articleInfoMapper.selectMaterialVideoUrl(articleInfo.getId()));
                articleRespEntity.setVideoUrl("");
                // 点赞数量
                //articleRespEntity.setLikeNum(this.articleInfoMapper.selectLikeNum(articleInfo.getId()));
                articleRespEntity.setLikeNum(0);
                // 素材图片
                String materialImgUrl = this.articleInfoMapper.selectMaterialImgUrl(articleInfo.getId());
                if (StringUtils.isNotBlank(materialImgUrl)){
                    articleRespEntity.setMaterialImgUrls(Arrays.asList(materialImgUrl.split(",")));
                }
                // 是否已经点赞
                //articleRespEntity.setIsLike(this.articleInfoMapper.isLike(userId,articleInfo.getId()));
                articleRespEntity.setIsLike(0);
                articleRespEntity.setResourceType(3);
                articleRespEntity.setVideoSize("1"); // 此字段用于前端控制 值随意
                return articleRespEntity;
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public int giveLikeByArticleId(Integer userId, Integer articleId) {
        if (null == userId && null == articleId){
            return -1;
        }
        // 查询是否已经点赞
        Integer num = Optional.ofNullable(this.articleInfoMapper.isLike(userId, articleId)).orElse(0);
        ArticleLikeInfo articleLikeInfo = new ArticleLikeInfo();
        articleLikeInfo.setUserId(userId);
        articleLikeInfo.setArticleId(articleId);
        if (num.equals(0)){
            //未点赞 需要点赞
            articleLikeInfo.setCreateTime(new Date());
            this.articleInfoMapper.addLike(articleLikeInfo);
            return 1;
        }
        // 删除点赞
        this.articleInfoMapper.delLike(articleLikeInfo);
        return 0;
    }

    @Override
    public int giveLikeStatusByArticleId(Integer userId, Integer articleId) {
        // 查询是否已经点赞
        Integer num = this.articleInfoMapper.isLike(userId, articleId);
        if (Objects.nonNull(num) && num.intValue() > 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public List<ArticleRespEntity> getArticle(Integer pageNum, Integer pageSize, GetArticleInfoByArticleReqBean articleInfoByArticleReqBean, Integer userId) {
        // 通过品牌id查询文章
        if (null != articleInfoByArticleReqBean.getArticleBrandId()){
            PageHelper.startPage(pageNum, pageSize);
            List<ArticleInfo>  articleInfos = this.articleInfoMapper.getArticleByBrandId(articleInfoByArticleReqBean.getArticleBrandId());
            if (CollectionUtils.isEmpty(articleInfos)){
                return null;
            }
            return  articleInfos.stream().map(articleInfo -> {
                ArticleRespEntity articleRespEntity = new ArticleRespEntity();
                articleRespEntity.setId(articleInfo.getId());
                articleRespEntity.setArticleDesc(articleInfo.getArticleDesc());
                articleRespEntity.setArticleShareCount(articleInfo.getArticleShareCount());
                articleRespEntity.setArticleHotScore(articleInfo.getArticleHotScore());

                articleRespEntity.setCreateTime(articleInfo.getCreateTime());
                articleRespEntity.setArticleImgUrl(articleInfo.getArticleImgUrl());
                articleRespEntity.setArticleTitle(articleInfo.getArticleTitle());
                // 相差分钟数
                articleRespEntity.setTimeDifference( this.timeDiffe(articleInfo.getCreateTime()));
                // 查询品牌名称和头像
                BrandInfo brandInfo = this.brandInfoMapper.selectBrandNameAndBrandHeadByBrandId(articleInfoByArticleReqBean.getArticleBrandId());
                if (null != brandInfo){
                    articleRespEntity.setHeadName(brandInfo.getBrandName());
                    articleRespEntity.setHeadImgUrl(brandInfo.getBrandLogo());
                }
                // 点赞数量
                articleRespEntity.setLikeNum(this.articleInfoMapper.selectLikeNum(articleInfo.getId()));
                // 是否已经点赞
                articleRespEntity.setIsLike(this.articleInfoMapper.isLike(userId,articleInfo.getId()));
                articleRespEntity.setResourceType(1);
                articleRespEntity.setVideoSize("1"); // 此字段用于前端控制 值随意
                return articleRespEntity;
            }).collect(Collectors.toList());
        }
        // 通过分类id查询
        if (null != articleInfoByArticleReqBean.getArticleTypeId()) {
            PageHelper.startPage(pageNum, pageSize);
            List<ArticleInfo> articleInfos = this.articleInfoMapper.getArticleByArticleTypeId(articleInfoByArticleReqBean.getArticleTypeId());
            if (CollectionUtils.isEmpty(articleInfos)) {
                return null;
            }
            return  articleInfos.stream().map(articleInfo -> {
                ArticleRespEntity articleRespEntity = new ArticleRespEntity();
                articleRespEntity.setId(articleInfo.getId());
                articleRespEntity.setArticleDesc(articleInfo.getArticleDesc());
                articleRespEntity.setArticleShareCount(articleInfo.getArticleShareCount());
                articleRespEntity.setArticleHotScore(articleInfo.getArticleHotScore());

                articleRespEntity.setCreateTime(articleInfo.getCreateTime());
                articleRespEntity.setArticleImgUrl(articleInfo.getArticleImgUrl());
                articleRespEntity.setArticleTitle(articleInfo.getArticleTitle());
                // 相差分钟数
                articleRespEntity.setTimeDifference( this.timeDiffe(articleInfo.getCreateTime()));
                // 查询分类名称和头像
                ArticleTypeInfo articleTypeInfo = this.articleTypeInfoMapper.selectBrandNameAndBrandHeadByTypeId(articleInfoByArticleReqBean.getArticleTypeId());
                if (null != articleTypeInfo){
                    articleRespEntity.setHeadName(articleTypeInfo.getArticleTypeName());
                    articleRespEntity.setHeadImgUrl(articleTypeInfo.getArticleTypeLogo());
                }
                // 点赞数量
                articleRespEntity.setLikeNum(this.articleInfoMapper.selectLikeNum(articleInfo.getId()));
                // 是否已经点赞
                articleRespEntity.setIsLike(this.articleInfoMapper.isLike(userId,articleInfo.getId()));
                articleRespEntity.setResourceType(1);
                articleRespEntity.setVideoSize("1"); // 此字段用于前端控制 值随意
                return articleRespEntity;
            }).collect(Collectors.toList());
        }
        // 无品牌id及分类id将返回关注的
        //-----------------------------------------------------------------------------------------
        // 用户关注的品牌
        List<UserBrandCombinedInfo> userBrandCombinedInfos = userBrandInfoMapper.queryUserBrandInfo(userId);
        // 关注的品牌id集合
        List<Integer> userBrandIds = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userBrandCombinedInfos)) {
            userBrandCombinedInfos.stream().forEach(info -> {
                userBrandIds.add(info.getBrandId());
            });
        }
        // 关注的类型id集合
        List<Integer> userConcernArticleTypeIds = this.connectionInfoService.getUserAttentionArticleTypeInfo(userId);
        if (CollectionUtils.isEmpty(userConcernArticleTypeIds)) {
            userConcernArticleTypeIds = userArticleTypeInfoService.getUserConcernArticleTypeInfo(userId);
            if (userConcernArticleTypeIds == null) {
                userConcernArticleTypeIds = Lists.newArrayList();
            }
            userConcernArticleTypeIds.add(1);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleInfo>  articleInfos = this.articleInfoMapper.getArticleByUserAttention(userBrandIds,userConcernArticleTypeIds);
        if (CollectionUtils.isNotEmpty(articleInfos)){
            return  articleInfos.stream().map(articleInfo -> {
                ArticleRespEntity articleRespEntity = new ArticleRespEntity();
                articleRespEntity.setId(articleInfo.getId());
                articleRespEntity.setArticleDesc(articleInfo.getArticleDesc());
                articleRespEntity.setArticleShareCount(articleInfo.getArticleShareCount());
                articleRespEntity.setArticleHotScore(articleInfo.getArticleHotScore());

                articleRespEntity.setCreateTime(articleInfo.getCreateTime());
                articleRespEntity.setArticleImgUrl(articleInfo.getArticleImgUrl());
                articleRespEntity.setArticleTitle(articleInfo.getArticleTitle());
                // 相差分钟数
                articleRespEntity.setTimeDifference( this.timeDiffe(articleInfo.getCreateTime()));
                // 查询名称和头像
                if (null != articleInfo.getArticleBrandId()){
                    BrandInfo brandInfo = this.brandInfoMapper.selectBrandNameAndBrandHeadByBrandId(articleInfo.getArticleBrandId());
                    if (null != brandInfo){
                        articleRespEntity.setHeadName(brandInfo.getBrandName());
                        articleRespEntity.setHeadImgUrl(brandInfo.getBrandLogo());
                    }
                }
                if (null != articleInfo.getArticleTypeId()){
                    ArticleTypeInfo articleTypeInfo = this.articleTypeInfoMapper.selectBrandNameAndBrandHeadByTypeId(articleInfo.getArticleTypeId());
                    if (null != articleTypeInfo){
                        articleRespEntity.setHeadName(articleTypeInfo.getArticleTypeName());
                        articleRespEntity.setHeadImgUrl(articleTypeInfo.getArticleTypeLogo());
                    }
                }
                // 点赞数量
                articleRespEntity.setLikeNum(this.articleInfoMapper.selectLikeNum(articleInfo.getId()));
                // 是否已经点赞
                articleRespEntity.setIsLike(this.articleInfoMapper.isLike(userId,articleInfo.getId()));
                articleRespEntity.setResourceType(1);
                articleRespEntity.setVideoSize("1"); // 此字段用于前端控制 值随意
                return articleRespEntity;
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<ArticleInfo> getArticleByVideo(Integer pageNum, Integer pageSize, GetArticleInfoByArticleReqBean articleInfoByArticleReqBean, Integer userId) {
        // 通过品牌id查询视频
        if (null != articleInfoByArticleReqBean.getArticleBrandId()){
            PageHelper.startPage(pageNum, pageSize);
            List<ArticleInfo>  articleInfos = this.articleInfoMapper.getVideoByBrandId(articleInfoByArticleReqBean.getArticleBrandId());
            if (CollectionUtils.isEmpty(articleInfos)){
                return null;
            }
            articleInfos.forEach(articleInfo -> articleInfo.setResourceType(2));
            return articleInfos;
        }
        //通过分类id查询
        if (null != articleInfoByArticleReqBean.getArticleTypeId()) {
            PageHelper.startPage(pageNum, pageSize);
            List<ArticleInfo> articleInfos = this.articleInfoMapper.getVideoByTypeId(articleInfoByArticleReqBean.getArticleTypeId());
            if (CollectionUtils.isEmpty(articleInfos)) {
                return null;
            }
            articleInfos.forEach(articleInfo -> {
                articleInfo.setResourceType(2);
                articleInfo.setArticleBrandName(articleInfo.getArticleTypeName());
            });
            return articleInfos;
        }
        // 无品牌id及分类id将返回关注的
        //-----------------------------------------------------------------------------------------
        // 用户关注的品牌
        List<UserBrandCombinedInfo> userBrandCombinedInfos = userBrandInfoMapper.queryUserBrandInfo(userId);
        // 关注的品牌id集合
        List<Integer> userBrandIds = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userBrandCombinedInfos)) {
            userBrandCombinedInfos.stream().forEach(info -> {
                userBrandIds.add(info.getBrandId());
            });
        }
        // 关注的类型id集合
        List<Integer> userConcernArticleTypeIds = this.connectionInfoService.getUserAttentionArticleTypeInfo(userId);
        if (CollectionUtils.isEmpty(userConcernArticleTypeIds)) {
            userConcernArticleTypeIds = userArticleTypeInfoService.getUserConcernArticleTypeInfo(userId);
            if (userConcernArticleTypeIds == null) {
                userConcernArticleTypeIds = Lists.newArrayList();
            }
            userConcernArticleTypeIds.add(1);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleInfo>  articleInfos = this.articleInfoMapper.getVideoByUserAttention(userBrandIds,userConcernArticleTypeIds);
        if (CollectionUtils.isNotEmpty(articleInfos)){
            articleInfos.stream().forEach(articleInfo -> {
                articleInfo.setResourceType(2);
                if (null != articleInfo.getArticleBrandId()){
                    BrandInfo brandInfo = this.brandInfoMapper.selectBrandNameAndBrandHeadByBrandId(articleInfo.getArticleBrandId());
                    if (null != brandInfo){
                        articleInfo.setArticleBrandId(null);
                        articleInfo.setArticleBrandName(brandInfo.getBrandName());
                    }
                }
                if (null != articleInfo.getArticleTypeId()){
                    ArticleTypeInfo articleTypeInfo = this.articleTypeInfoMapper.selectBrandNameAndBrandHeadByTypeId(articleInfo.getArticleTypeId());
                    if (null != articleTypeInfo){
                        articleInfo.setArticleTypeId(null);
                        articleInfo.setArticleTypeName(articleTypeInfo.getArticleTypeName());
                        articleInfo.setArticleBrandName(articleTypeInfo.getArticleTypeName());
                    }
                }
            });
            return articleInfos;
        }
        return null;
    }

    @Override
    public List<String> selectMaterialImgByArticleId(Integer articleId) {
        String materialImgUrl = this.articleInfoMapper.selectMaterialImgUrl(articleId);
        if (StringUtils.isNotBlank(materialImgUrl)){
           return Arrays.asList(materialImgUrl.split(","));
        }
        return null;
    }

    @Override
    public boolean isSaveLocally(Integer userId, Integer articleId, String gzhCode) {
        // 查询该用户今天查看的素材列表
        List<Integer> articleIds = this.articleInfoMapper.selectCheckList(userId,gzhCode);
        if (articleIds!=null && articleIds.contains(articleId)){
            return this.articleInfoMapper.selectIsSaveLocalByArticleId(userId, articleId, gzhCode) == 1;
        }
        // 查询用户是否为vip
        Integer vipStatus = Optional.ofNullable(this.userInfoService.getUserVipStatus(userId)).orElse(0);
        // 查询用户今天可以保存的次数
        Integer saveNum= this.articleInfoMapper.saveLocallyNum(gzhCode,vipStatus);
        // 查询该用户今天查看次数
        Integer checkNum=this.articleInfoMapper.selectCheckNum(userId,gzhCode);
        Integer isSaveLocal =0;
        if (checkNum.compareTo(saveNum) < 0){
            isSaveLocal=1;
        }
        // 记录本次访问
        this.articleInfoMapper.addCheckRecord(userId,articleId,gzhCode,isSaveLocal);
        return isSaveLocal == 1;
    }

    @Override
    public void addUserAttentionMaterial(ArticleRespEntity articleRespEntity) {
        // 插入素材
        this.articleInfoMapper.addUserAttentionMaterial(articleRespEntity);
       // 将图片地址写入素材库
        if (StringUtils.isNotBlank(articleRespEntity.getMaterialImgUrl())){
            this.articleInfoMapper.insertMaterialImg(articleRespEntity.getId(),articleRespEntity.getMaterialImgUrl());
        }
    }

    @Override
    public List<ArticleRespEntity> selectMaterialByUserId(Integer pageNum, Integer pageSize, Integer userId) {
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleInfo> articleInfos = this.articleInfoMapper.selectMaterialByUserId(userId);
        if (CollectionUtils.isEmpty(articleInfos)){
            return null;
        }
        return articleInfos.stream().map(articleInfo -> {
            ArticleRespEntity articleRespEntity = new ArticleRespEntity();
            articleRespEntity.setId(articleInfo.getId());
            articleRespEntity.setArticleDesc(articleInfo.getArticleDesc());
            articleRespEntity.setArticleShareCount(articleInfo.getArticleShareCount());
            articleRespEntity.setArticleStatus(articleInfo.getArticleStatus());
            // 相差分钟数
            articleRespEntity.setTimeDifference( this.timeDiffe(articleInfo.getCreateTime()));
            if(null != articleInfo.getArticleTypeId()){
                // 查询分类名称和头像
                ArticleTypeInfo articleTypeInfo = this.articleTypeInfoMapper.selectBrandNameAndBrandHeadByTypeId(articleInfo.getArticleTypeId());
                if (null != articleTypeInfo){
                    articleRespEntity.setHeadName(articleTypeInfo.getArticleTypeName());
                    articleRespEntity.setHeadImgUrl(articleTypeInfo.getArticleTypeLogo());
                }
            }else if(null != articleInfo.getArticleBrandId()){
                // 查询品牌名称和头像
                BrandInfo articleTypeInfo2 = this.brandInfoMapper.selectBrandInfoAndBrandHeadByTypeId(articleInfo.getArticleBrandId());
                if (null != articleTypeInfo2){
                    articleRespEntity.setHeadName(articleTypeInfo2.getBrandName());
                   articleRespEntity.setHeadImgUrl(articleTypeInfo2.getBrandLogo());
                }
            }
            // 点赞数量
            articleRespEntity.setLikeNum(this.articleInfoMapper.selectLikeNum(articleInfo.getId()));
            // 素材图片
            String materialImgUrl = this.articleInfoMapper.selectMaterialImgUrl(articleInfo.getId());
            if (StringUtils.isNotBlank(materialImgUrl)){
                articleRespEntity.setMaterialImgUrls(Arrays.asList(materialImgUrl.split(",")));
            }
            // 是否已经点赞
            articleRespEntity.setIsLike(this.articleInfoMapper.isLike(userId,articleInfo.getId()));
            articleRespEntity.setResourceType(3);
            articleRespEntity.setVideoSize("1"); // 此字段用于前端控制 值随意
            return articleRespEntity;
        }).collect(Collectors.toList());

    }

    @Override
    public void delMaterialById(ArticleInfo articleInfo) {
        // 删除素材 物理删除
        this.articleInfoMapper.delMaterialById(articleInfo);
        // 删除素材图片 物理删除
        this.articleInfoMapper.delMateriaImglById(articleInfo.getId());
    }


    /**
     * 计算时间差
     *
     * @param  date 创建时间
     * @return
     */
    private String timeDiffe(Date date){
        int min = DateUtil.getTimeDiff(2, date);
        if (min <= 0){
            return "刚刚";
        }else if(min < 60){
            return min+"分钟之前";
        }else if (min < 60 * 24){
           return DateUtil.getTimeDiff(3,date)+"小时之前";
        }else if (min < 60 * 24 * 30){
            return DateUtil.getTimeDifference(4,date)+"天之前";
        } else if (min < 60 * 24 * 30 * 12){
           return DateUtil.getTimeDifference(5,date)+"个月之前";
        } else if (min > 60 * 24 * 30 * 12){
           return DateUtil.getTimeDifference(6,date)+"年之前";
        }else {
            return "0";
        }
    }

    @Override
    public int addMaterialVideoByInfo(ArticleInfo articleInfo) {
        // 插入视频文章
        ArticleInfo articleInfoDto = new ArticleInfo();

        articleInfoDto.setArticleTitle(articleInfo.getArticleTitle());
        articleInfoDto.setArticleImgUrl(articleInfo.getArticleImgUrl());
        articleInfoDto.setArticleBrandId(articleInfo.getArticleBrandId());
        articleInfoDto.setArticleTypeId(articleInfo.getArticleTypeId());
        articleInfoDto.setUserId(articleInfo.getUserId());//创建人
        articleInfoDto.setArticleSource(3);
        articleInfoDto.setArticleStatus(1);
//        articleInfoDto.setShareArticleSourceId(articleId);
        articleInfoDto.setArticleContent(articleInfo.getArticleContent());
        articleInfoDto.setSpiderProcessStatus(1);
        articleInfoDto.setArticleVersionNum(2);
        articleInfoDto.setsType("用户添加");
        articleInfoDto.setResourceType(2);//视频
        articleInfoDto.setVideoFormat(".mp4");
        articleInfoDto.setVideoSize(articleInfo.getVideoSize());
        articleInfoDto.setVideoUrl(articleInfo.getVideoUrl());
        articleInfoDto.setArticleDesc(articleInfo.getArticleTitle());//分享配文
        articleInfoDto.setVideoHeight(articleInfo.getVideoHeight());//视频高度
        articleInfoDto.setCreateTime(DateUtil.getCurDate());
        articleInfoDto.setModifyTime(DateUtil.getCurDate());

        this.articleInfoMapper.addArticleInfo(articleInfoDto);
        // 设置用户文章底部开关的开启状态
        saveUserArticleTailSetInfo(articleInfo.getUserId(), articleInfo.getId());
        return articleInfoDto.getId();
    }

    @Override
    public int addMaterialVideoByDouDouInfo(ArticleInfo ArticleInfo) {
        // 插入视频文章
        ArticleInfo articleInfoDto = new ArticleInfo();

        articleInfoDto.setArticleTitle(ArticleInfo.getArticleTitle());
        articleInfoDto.setArticleImgUrl(ArticleInfo.getArticleImgUrl());
        articleInfoDto.setArticleBrandId(ArticleInfo.getArticleBrandId());
        articleInfoDto.setArticleTypeId(ArticleInfo.getArticleTypeId());
        articleInfoDto.setUserId(ArticleInfo.getUserId());//创建人
        articleInfoDto.setArticleSource(2);
        articleInfoDto.setArticleStatus(1);
//        articleInfoDto.setShareArticleSourceId(articleId);
        articleInfoDto.setArticleContent(ArticleInfo.getArticleContent());
        articleInfoDto.setSpiderProcessStatus(1);
        articleInfoDto.setArticleVersionNum(2);
        articleInfoDto.setsType(ArticleInfo.getsType());
        articleInfoDto.setResourceType(2);//视频
        articleInfoDto.setVideoFormat(".mp4");
        articleInfoDto.setVideoSize(ArticleInfo.getVideoSize());
        articleInfoDto.setVideoUrl(ArticleInfo.getVideoUrl());
        articleInfoDto.setArticleDesc(ArticleInfo.getArticleDesc());//分享配文
        articleInfoDto.setVideoHeight(ArticleInfo.getVideoHeight());//视频高度
        articleInfoDto.setCreateTime(DateUtil.getCurDate());
        articleInfoDto.setModifyTime(DateUtil.getCurDate());

        this.articleInfoMapper.addMaterialVideoByDouDouInfo(articleInfoDto);
        // 设置用户文章底部开关的开启状态
        saveUserArticleTailSetInfo(ArticleInfo.getUserId(), articleInfoDto.getId());

        return articleInfoDto.getId();
    }

    @Override
    public int updateMaterialVideoByInfo(ArticleInfo ArticleInfo) {
        // 插入视频文章
        ArticleInfo articleInfoDto = new ArticleInfo();

        articleInfoDto.setId(ArticleInfo.getId());
        articleInfoDto.setArticleTitle(ArticleInfo.getArticleTitle());
        articleInfoDto.setModifyTime(DateUtil.getCurDate());

        this.articleInfoMapper.updateArticleInfo(articleInfoDto);
        return articleInfoDto.getId();
    }

    /**
     * 常见问题 id ，公众号标识，查询 常见问题 多条数据
     *
     * @param pageNum 查询起始位置
     * @param pageSize  查询条数
     * @param articleTypeId 品牌 常见问题id
     * @param gzhCode 公众号标识
     * @return 对象列表
     */
    @Override
    public PageInfo selectManualByLimit(Integer pageNum , Integer pageSize, Integer articleTypeId, String gzhCode) {

        PageHelper.startPage(pageNum, pageSize);

        List<CombinedArticleInfoByArticleBrand> articleInfoList = this.articleInfoMapper.selectManualByLimit(articleTypeId, gzhCode);

        // 专业号过滤指定常见问题 id文章
        if (gzhCode.equalsIgnoreCase("prodzx1") ||
                gzhCode.equalsIgnoreCase("prodhyxt") ||
                gzhCode.equalsIgnoreCase("prodhysck") ||
                gzhCode.equalsIgnoreCase("prodtxp") ||
                gzhCode.equalsIgnoreCase("prodzgts") ||
                gzhCode.equalsIgnoreCase("prodbdxzs")||
                gzhCode.equalsIgnoreCase("back_zkt")||
                gzhCode.equalsIgnoreCase("prodshjj")||
                gzhCode.equalsIgnoreCase("prodshsck")||
                gzhCode.equalsIgnoreCase("prodmyds")||
                gzhCode.equalsIgnoreCase("prodkdxsq")||
                gzhCode.equalsIgnoreCase("prodbkwz")) {

            // 3756442 - 如何设置自己的品牌文章？, 4075932 - 如何找到自己的品牌文章/视频？
            articleInfoList = articleInfoList.stream().filter(obj ->
                    (obj.getArticleId() != 3756442 && obj.getArticleId() != 4075932)
            ).collect(Collectors.toList());
        }

        return new PageInfo<CombinedArticleInfoByArticleBrand>(articleInfoList);
    }

    /**
     * 根据 品牌id 或 分类id 查询最新文章或视频多条数据
     *
     * @param pageNum 页码
     * @param pageSize 每页数
     * @param type 1-品牌文章 2-分类文章
     * @param articleBrandIdOrTypeId 品牌id 或 分类id
     * @return
     */
    @Override
    public PageInfo<CombinedArticleInfoByArticleBrandAndHotValue> getArticleByBrandIdOrTypeId(Integer pageNum , Integer pageSize, Integer type, Integer articleBrandIdOrTypeId) {
        PageHelper.startPage(pageNum, pageSize);

        List<CombinedArticleInfoByArticleBrandAndHotValue> articleInfoByArticleBrandList = articleInfoMapper.getArticleByBrandIdOrTypeId(type, articleBrandIdOrTypeId);

        return new PageInfo<CombinedArticleInfoByArticleBrandAndHotValue>(articleInfoByArticleBrandList);
    }

    @Override
    public List<CombinedArticleInfoByArticleBrandAndHotValue> queryUserArticleInfoByUserId(Integer userId, int recordSize) {
        return articleInfoMapper.queryUserArticleInfoByUserId(userId, recordSize);
    }


    @Override
    public List<CombinedArticleInfoByArticleBrand> queryArticleInfoOfBrandOrType(Integer type, Integer articleBrandIdOrTypeId, int recordSize) {

        return articleInfoMapper.queryArticleInfoOfBrandOrType(type, articleBrandIdOrTypeId, recordSize);
    }

    /**
     * redis 取品牌文章Top50
     * @param articleBrandId
     * @param recordSize
     * @return
     */
    @Override
    public List<CombinedArticleInfoByArticleBrand> getArticleInfoByBrandForRandTop50(Integer articleBrandId, int recordSize) {
        String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + articleBrandId;

        Set<CombinedArticleInfoByArticleBrand> brandArticleInfoSet = redisCacheUtil.getMasterCacheSetForRandomEle(articleBrandIdKey, recordSize);

        List<CombinedArticleInfoByArticleBrand> brandArticleInfoList = Lists.newArrayList();

        if (CollectionUtils.isNotEmpty(brandArticleInfoSet)) {
            brandArticleInfoList = Lists.newArrayList(brandArticleInfoSet);
        } else {
            setArticleInfoByBrandForRandTop50(articleBrandId);

            redisCacheUtil.getMasterCacheSetForRandomEle(articleBrandIdKey, recordSize);
            brandArticleInfoList = Lists.newArrayList(brandArticleInfoSet);
        }

        return brandArticleInfoList;
    }

    /**
     * redis 存品牌文章Top50
     * @param articleBrandId
     */
    public void setArticleInfoByBrandForRandTop50(Integer articleBrandId) {
        List<CombinedArticleInfoByArticleBrand> articleInfos = articleInfoMapper.queryArticleInfoOfBrandOrType(1, articleBrandId, 50);
        if (CollectionUtils.isNotEmpty(articleInfos)) {
            articleInfos.stream().forEach(info -> {

                String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + info.getArticleBrandId();
                Long result = redisCacheUtil.addEleToSet(articleBrandIdKey, info);

                log.info("[AddEleCountIn " + articleBrandIdKey + "] = " + result);
            });

        }
    }

    /**
     * redis 取分类文章Top50
     * @param articleTypeId
     * @param recordSize
     * @return
     */
    @Override
    public List<CombinedArticleInfoByArticleBrand> getArticleInfoByArticleTypeForRandTop50(Integer articleTypeId, int recordSize) {

        String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + articleTypeId;

        Set<CombinedArticleInfoByArticleBrand> typeArticleInfoSet = redisCacheUtil.getMasterCacheSetForRandomEle(articleTypeIdKey, recordSize);

        List<CombinedArticleInfoByArticleBrand> typeArticleInfoList = Lists.newArrayList();

        if (CollectionUtils.isNotEmpty(typeArticleInfoSet)) {
            typeArticleInfoList = Lists.newArrayList(typeArticleInfoSet);
        } else {
            setArticleInfoByArticleTypeForRandTop50(articleTypeId);

            typeArticleInfoSet = redisCacheUtil.getMasterCacheSetForRandomEle(articleTypeIdKey, recordSize);
            typeArticleInfoList = Lists.newArrayList(typeArticleInfoSet);
        }

        return typeArticleInfoList;
    }

    /**
     * redis 存分类文章Top50
     * @param articleTypeId
     */
    public void setArticleInfoByArticleTypeForRandTop50(Integer articleTypeId) {
        List<CombinedArticleInfoByArticleBrand> articleInfos = articleInfoMapper.queryArticleInfoOfBrandOrType(2, articleTypeId, 50);
        if (CollectionUtils.isNotEmpty(articleInfos)) {

            articleInfos.stream().forEach(info -> {

                String articleTypeIdKey = SysConstant.PLANT_FORM_TYPE_ARTICLE_TOP50 + info.getArticleTypeId();
                Long result = redisCacheUtil.addEleToSet(articleTypeIdKey, info);

                log.info("[AddEleOfTypeCountIn " + articleTypeIdKey + "] = " + result);
            });
        }
    }

    /**
     * 如果该品牌没有文章了，那么就找关联品牌文章，如果没有关联品牌就找关联分类文章
     *
     * @param articleBrandId
     * @return
     */
    @Override
    public List<ArticleListShowInfo> getLinkArticle(Integer articleBrandId) {

        List<ArticleListShowInfo> linkArticle = Lists.newArrayList();
        // 补位关联品牌
        Integer linkBrand = Optional.ofNullable(brandInfoMapper.queryLinkBrandByBrandId(articleBrandId)).orElse(0);

        if (linkBrand != 0) {
            // 补位关联品牌文章
            List<CombinedArticleInfoByArticleBrand> articleInfoByArticleBrandList = articleInfoMapper.getLinkArticle(1, linkBrand, 5);

            if (articleInfoByArticleBrandList != null && articleInfoByArticleBrandList.size() > 0) {
                for(CombinedArticleInfoByArticleBrand info : articleInfoByArticleBrandList){
                    ArticleListShowInfo e = new ArticleListShowInfo();
                    e.setArticleId(info.getArticleId());
                    e.setArticleBrandId(info.getArticleBrandId());
                    e.setArticleBrandName(brandInfoMapper.queryBrandInfoByBrandId(linkBrand));
                    e.setArticleTypeId(info.getArticleTypeId());
                    e.setArticleImgUrl(info.getArticleImgUrl());
                    e.setArticleTitle(info.getArticleTitle());

                    e.setResourceType(info.getResourceType());
                    e.setArticleHotValue(ToolUtil.setArticleHotValue(0));
                    e.setArticleVersionNum(info.getArticleVersionNum());

                    linkArticle.add(e);
                }
                return linkArticle;
            }
        }

        List<BrandSupplyInfo> brandSupplyInfoList = brandSupplyInfoMapper.queryBrandSupplyInfo(articleBrandId);

        if (brandSupplyInfoList != null && brandSupplyInfoList.size() > 0 && brandSupplyInfoList.get(0).getArticleTypeId() != null  ) {
            // 补位关联分类
            Integer linkType = Optional.ofNullable(brandSupplyInfoList.get(0).getArticleTypeId()).orElse(0);

            if (linkType != 0) {
                // 补位关联分类文章
                List<CombinedArticleInfoByArticleBrand> articleInfoByArticleTypeList = articleInfoMapper.getLinkArticle(2, linkType, 5);

                if (articleInfoByArticleTypeList != null && articleInfoByArticleTypeList.size() > 0) {
                    for(CombinedArticleInfoByArticleBrand info : articleInfoByArticleTypeList){
                        ArticleListShowInfo e = new ArticleListShowInfo();
                        e.setArticleId(info.getArticleId());
                        e.setArticleBrandId(info.getArticleBrandId());
                        e.setArticleTypeId(info.getArticleTypeId());
                        e.setArticleTypeName(articleTypeInfoMapper.getTypeInfoByTypeId(linkType));

                        e.setArticleBrandName(articleTypeInfoMapper.getTypeInfoByTypeId(linkType));

                        e.setArticleImgUrl(info.getArticleImgUrl());
                        e.setArticleTitle(info.getArticleTitle());

                        e.setResourceType(info.getResourceType());
                        e.setArticleHotValue(ToolUtil.setArticleHotValue(0));
                        e.setArticleVersionNum(info.getArticleVersionNum());

                        linkArticle.add(e);
                    }
                    return linkArticle;
                }
            }
        }

        return linkArticle;
    }

    @Override
    public List<ArticleInfo> getUserCreateOrModifyArticle(Integer userId, Integer type) {
        return articleInfoMapper.getUserCreateOrModifyArticle(userId, type);
    }

    @Override
    public UserArticleTailSetInfo getArticleTailSetInfo(Integer userId, Integer articleId) {
        return articleTailSetInfoMapper.getArticleTailSetInfo(userId, articleId);
    }

    @Override
    public int addArticleTailSetInfo(ArticleTailSetInfo articleTailSetInfo) {
        return articleTailSetInfoMapper.addArticleTailSetInfo(articleTailSetInfo);
    }

    @Override
    public int updateArticleTailSetInfo(ArticleTailSetInfo articleTailSetInfo) {
        return articleTailSetInfoMapper.updateArticleTailSetInfo(articleTailSetInfo);
    }

    @Override
    public List<CombinedCustomerInfo> getCurrentWeekPublishData(Integer userId) {
        Date currentDate = DateUtil.getCurDate();
        String firstDayOfWeek = DateUtil.getFirstDayOfWeek(currentDate);
        String lastDayOfWeek = DateUtil.getLastDayOfWeek(currentDate);
        return articleInfoMapper.getCurrentWeekPublishData(userId, firstDayOfWeek, lastDayOfWeek);
    }

    @Override
    public List<CombinedCustomerInfo> getCurrentMonthPublishData(Integer userId) {
        Date currentDate = DateUtil.getCurDate();
        String firstDayOfMonth = DateUtil.getFirstDayOfMonth(currentDate);
        String lastDayOfMonth = DateUtil.getLastDayOfMoth(currentDate);
        return articleInfoMapper.getCurrentMonthPublishData(userId, firstDayOfMonth, lastDayOfMonth);
    }

    @Override
    public List<CombinedCustomerYearInfo> getCurrentSeasonPublishData(Integer userId) {
        // 按天统计
//        String firstDayOfSeason = DateUtil.getFirstDayOfSeason();
//        String lastDayOfSeason = DateUtil.getLastDayOfSeason();
//        return articleInfoMapper.getCurrentSeasonPublishData(userId, firstDayOfSeason, lastDayOfSeason);

        // 按月统计
        Integer firstMonthOfSeason = Integer.valueOf(DateUtil.getFirstMonthOfSeason());
        Integer lastMonthOfSeason = Integer.valueOf(DateUtil.getLastMonthOfSeason());
        return articleInfoMapper.getCurrentSeasonPublishDataByMonth(userId, firstMonthOfSeason, lastMonthOfSeason);
    }

    @Override
    public List<CombinedCustomerYearInfo> getCurrentYearPublishData(Integer userId) {
        return articleInfoMapper.getCurrentYearPublishData(userId);
    }

    @Override
    public int getArticleLikeCount(Integer articleId) {
        return Optional.ofNullable(articleInfoMapper.selectLikeNum(articleId)).orElse(0);
    }

    /**
     * 保存用户文章底部开关的开启状态
     * @param userId 用户 ID
     * @param articleId 文章 ID
     * @return 主键 ID
     */
    private Integer saveUserArticleTailSetInfo(Integer userId, Integer articleId) {
        Integer advertSwitchStatus = Integer.valueOf(1);// 广告总开关 0-关闭 1-启用 默认启用
        Integer tableSwitchStatus = Integer.valueOf(1);// 文章底部表格总开关 0-关闭 1-启用 默认启用

        // 获取用户广告和文章底部表格总开关开启状态信息
        UserArticleTailSwitchSet userArticleTailSwitchSet = wxNotifyMsgSetInfoMapper.queryUserArticleTailSwitch(userId);
        if (Objects.nonNull(userArticleTailSwitchSet)) {
            advertSwitchStatus = Optional.ofNullable(userArticleTailSwitchSet.getAdvertSwitchStatus()).orElse(1);
            tableSwitchStatus = Optional.ofNullable(userArticleTailSwitchSet.getTableSwitchStatus()).orElse(1);
        }

        ArticleTailSetInfo articleTailSetInfo = new ArticleTailSetInfo();
        articleTailSetInfo.setUserId(userId);
        articleTailSetInfo.setArticleId(articleId);
        articleTailSetInfo.setArticleAdvertSwitchStatus(advertSwitchStatus);
        articleTailSetInfo.setArticleTableSwitchStatus(tableSwitchStatus);
        articleTailSetInfo.setCreateTime(DateUtil.getCurDate());

        return articleTailSetInfoMapper.addArticleTailSetInfo(articleTailSetInfo);
    }

}
